package com.ztn.iot.zhonghaichi2.push2;

import com.ztn.base.util.common.JsonTool;
import com.ztn.iot.zhonghaichi2.properties.ZhcProperties2;
import com.ztn.iot.zhonghaichi2.push2.res.CameraRes;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

@Data
@Slf4j
@Component
public class CameraPushApi2 {

    @Autowired
    private ZhcProperties2 zhcProperties2;


    public CameraRes push(String deviceId, String deviceSecret, File file) throws IOException, NoSuchAlgorithmException, InvalidKeyException {

        String resourceName = "products/" + zhcProperties2.getProductId() + "/devices/" + deviceId;
        String expirationTime = System.currentTimeMillis() / 1000 + 100 * 24 * 60 * 60 + "";
        String accessKey = deviceSecret;
        String token = TokenUtil.assembleToken(zhcProperties2.getVersion(), resourceName, expirationTime, zhcProperties2.getSignatureMethod(), accessKey);


        OkHttpClient client = new OkHttpClient()
                .newBuilder()
                .connectTimeout(2, TimeUnit.MINUTES)
                .readTimeout(2, TimeUnit.MINUTES)
                .writeTimeout(2, TimeUnit.MINUTES)
                .build();
//        MediaType mediaType = MediaType.parse("multipart/form-data");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("filename", System.currentTimeMillis()+"_"+file.getName())
                .addFormDataPart("md5", DigestUtils.md5Hex(new FileInputStream(file)))
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .addFormDataPart("size", String.valueOf(file.length()))
                .build();
        Request request = new Request.Builder()
                .url("http://iot.gdwater.gov.cn:8080/iotgz/file-system/studio/" + zhcProperties2.getProductId() + "/" + deviceId + "/outupload")
                .method("POST", body)
                .addHeader("Authorization", token)
                .addHeader("Content-Type", "multipart/form-data")
                .build();

        Response response = client.newCall(request).execute();
        String resString = response.body().string();
        log.info("okHttpGet run: response: {}", resString);
        CameraRes cameraRes = JsonTool.fromJson(resString,CameraRes.class);
//        file.delete();
        return cameraRes;

    }

}
